
package net.starwifi.duobao.web;

import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.mvc.BaseController;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.oauth.Principal;
import net.starwifi.duobao.service.GglUserService;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.service.RSAService;
import net.starwifi.duobao.utils.IpUtils;
import net.starwifi.duobao.utils.WebUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;

/**
 * Controller - 会员登录
 * 
 * @author ruoo
 * @version 1.0
 */
@Controller("appLoginController")
public class LoginController extends BaseController {


	@Autowired
	private RSAService rsaService;

	@Autowired
	private MemberService memberService;

	@Autowired
	GglUserService gglUserService;



	/**
	 * 登录(网页)
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public  Object login(Model model,String redirectUrl) {
		model.addAttribute("redirectUrl",redirectUrl);
		return "login/login";
	}

	/**
	 * 用户注册
	 * @param model
	 * @param redirectUrl
	 * @return
	 */
	@RequestMapping(value = "/reg", method = RequestMethod.GET)
	public  Object reg(Model model,String redirectUrl) {
		model.addAttribute("redirectUrl",redirectUrl);
		return "login/reg";
	}

	/**
	 * 登录检测
	 */
	@RequestMapping(value = "/check", method = RequestMethod.GET)
	public @ResponseBody
	Boolean check() {
		return memberService.isAuthenticated();
	}

	/**
	 * 登录提交
	 */
	@ResponseBody
	@RequestMapping(value = "/login_validate", method = RequestMethod.POST)
	public Object submit(String username,String password, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		//String password = rsaService.decryptParameter("password", request);
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			return Message.error("用户名或者密码不能为空");
		}
		final Member member= memberService.findByMobile(username);;
		if (member == null) {
			return Message.error("用户名或者密码错误");
		}
		if (!member.getIsEnabled()) {
			return Message.error("账户已禁用，请联系客服");
		}
		if(!DigestUtils.md5Hex(password+member.getSalt()).equals(member.getPassword())){
			return Message.error("用户名或者密码错误");
		}
 		member.setLoginIp(request.getRemoteAddr());
		member.setLoginDate(new Date());
		member.setLoginFailureCount(0);
		memberService.update(member);
		Map<String, Object> attributes = new HashMap<String, Object>();
		Enumeration<?> keys = session.getAttributeNames();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			attributes.put(key, session.getAttribute(key));
		}
		session.invalidate();
		session = request.getSession();
		for (Entry<String, Object> entry : attributes.entrySet()) {
			session.setAttribute(entry.getKey(), entry.getValue());
		}
		String userAgent=request.getHeader("User-Agent");
		String cookiePass=DigestUtils.md5Hex(userAgent + member.getPassword());
		session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), username));
		WebUtils.addCookie(request, response, Member.COOKIE_USERNAME_NAME, member.getUsername());
		WebUtils.addCookie(request, response, Member.COOKIE_PASS_NAME, cookiePass);
		return Message.createMessage(Message.success("登陆成功"), new HashMap<String, Object>() {{
			put("entity",member);
		}});
	}

	/**
	 * 登录提交
	 */
	@ResponseBody
	@RequestMapping(value = "/wapLoginValidate", method = RequestMethod.POST)
	public Object wapLoginValidate(String username, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		String password = rsaService.decryptParameter("password", request);
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			return Message.error("用户名或者密码不能为空");
		}
		final Member member= memberService.findByMobile(username);;
		if (member == null) {
			return Message.error("用户名或者密码错误");
		}
		if (!member.getIsEnabled()) {
			return Message.error("账户已禁用，请联系客服");
		}
		if(!DigestUtils.md5Hex(password+member.getSalt()).equals(member.getPassword())){
			return Message.error("用户名或者密码错误");
		}
		member.setLoginIp(request.getRemoteAddr());
		member.setLoginDate(new Date());
		member.setLoginFailureCount(0);
		if(session.getAttribute("cp")!=null){ //CP 渠道商标识
			member.setCpId(session.getAttribute("cp").toString());
		}
		memberService.update(member);
		//获取登录时间
		gglUserService.saveLog(member);
		Map<String, Object> attributes = new HashMap<String, Object>();
		Enumeration<?> keys = session.getAttributeNames();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			attributes.put(key, session.getAttribute(key));
		}
		session.invalidate();
		session = request.getSession();
		for (Entry<String, Object> entry : attributes.entrySet()) {
			session.setAttribute(entry.getKey(), entry.getValue());
		}
		String userAgent=request.getHeader("User-Agent");
		String cookiePass=DigestUtils.md5Hex(userAgent + member.getPassword());
		session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), username));
		WebUtils.addCookie(request, response, Member.COOKIE_USERNAME_NAME, member.getUsername());
		WebUtils.addCookie(request, response, Member.COOKIE_PASS_NAME, cookiePass);
		return Message.createMessage(Message.success("登陆成功"), new HashMap<String, Object>() {{
			put("entity",member);
		}});
	}


	/**
	 * 登录提交
	 */
	@ResponseBody
	@RequestMapping(value = "/wapMobileLogin", method = RequestMethod.POST)
	public Object wapMobileLogin(String username,String smsCode, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(smsCode)) {
			return Message.error("用户名或者验证码不能为空");
		}
		String cacheKey="sms_wapLogin_"+username;
		if(request.getSession().getAttribute(cacheKey)==null){
			return Message.error("验证码错误");
		}
		String sessionCode=(String)request.getSession().getAttribute(cacheKey);
		if(!sessionCode.equals(smsCode)){
			return Message.error("验证码错误");
		}
		 Member member= memberService.findByMobile(username);;
		if (member == null) {
			member=new Member();
			member.setUsername("m" + username);
			String salt= net.starwifi.duobao.utils.StringUtils.getUUID();
			member.setSalt(salt);
			member.setMobile(username);
			member.setIsEnabled(true);
			member.setIsLocked(false);
			member.setLoginFailureCount(0);
			member.setLockedDate(null);
			member.setBalance(BigDecimal.ZERO);
			member.setCurrencyBalance(BigDecimal.ZERO);
			member.setVirtualCurrency(BigDecimal.ZERO);
			try {
				if(request.getSession().getAttribute("cp")!=null){
					member.setCpId((String)request.getSession().getAttribute("cp"));
				}
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		if (!member.getIsEnabled()) {
			return Message.error("账户已禁用，请联系客服");
		}
		if(member.getVirtualCurrency()==null){
			member.setVirtualCurrency(BigDecimal.ZERO);
		}
		member.setLoginIp(IpUtils.getIpAddr(request));
		member.setLoginDate(new Date());
		member.setLoginFailureCount(0);
		if(member.getId()==null){
			memberService.save(member);
		}else{
			memberService.update(member);
		}
		//获取登录时间
		gglUserService.saveLog(member);
		Map<String, Object> attributes = new HashMap<String, Object>();
		Enumeration<?> keys = session.getAttributeNames();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			attributes.put(key, session.getAttribute(key));
		}
		session.invalidate();
		session = request.getSession();
		for (Entry<String, Object> entry : attributes.entrySet()) {
			session.setAttribute(entry.getKey(), entry.getValue());
		}
		String userAgent=request.getHeader("User-Agent");
		String cookiePass=DigestUtils.md5Hex(userAgent + member.getPassword());
		session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), username));
		session.setAttribute("pMobile",username);
		WebUtils.addCookie(request, response, Member.COOKIE_USERNAME_NAME, member.getUsername());
		WebUtils.addCookie(request, response, Member.COOKIE_PASS_NAME, cookiePass);
		return Message.success("登陆成功");
	}

	@ResponseBody
	@RequestMapping(value = "/reg_validate", method = RequestMethod.POST)
	public Object regSubmit(String username,String password,String smsCode, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		//String password = rsaService.decryptParameter("password", request);
		if(StringUtils.isEmpty(smsCode)){
			return Message.error("验证码不能为空");
		}
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) ) {
			return Message.error("用户名或者密码不能为空");
		}
		String cacheKey="sms_register_"+username;
		if(request.getSession().getAttribute(cacheKey)==null){
			return Message.error("验证码错误");
		}
		String sessionCode=(String)request.getSession().getAttribute(cacheKey);
		if(!sessionCode.equals(smsCode)){
			return Message.error("验证码错误");
		}
		 Member member= memberService.findByMobile(username);;
		if (member != null) {
			return Message.error("用户已存在，请直接登录");
		}

		if (member == null) {
			member=new Member();
			member.setUsername("m" + username);
			String salt= net.starwifi.duobao.utils.StringUtils.getUUID();
			member.setSalt(salt);
			member.setPassword(DigestUtils.md5Hex(password + salt));
			member.setMobile(username);
			member.setIsEnabled(true);
			member.setIsLocked(false);
			member.setLoginFailureCount(0);
			member.setLockedDate(null);
			member.setLoginIp(request.getRemoteAddr());
			member.setLoginDate(new Date());
			member.setBalance(BigDecimal.ZERO);
			member.setCurrencyBalance(BigDecimal.ZERO);
			member.setVirtualCurrency(BigDecimal.ZERO);
			try {
				if(request.getSession().getAttribute("cp")!=null){
					member.setCpId((String)request.getSession().getAttribute("cp"));
				}
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		memberService.save(member);
//		Map<String, Object> attributes = new HashMap<String, Object>();
//		Enumeration<?> keys = session.getAttributeNames();
//		while (keys.hasMoreElements()) {
//			String key = (String) keys.nextElement();
//			attributes.put(key, session.getAttribute(key));
//		}
//		session.invalidate();
//		session = request.getSession();
//		for (Entry<String, Object> entry : attributes.entrySet()) {
//			session.setAttribute(entry.getKey(), entry.getValue());
//		}
//		String userAgent=request.getHeader("User-Agent");
//		String cookiePass=DigestUtils.md5Hex(userAgent + member.getPassword());
//		session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), username));
//		WebUtils.addCookie(request, response, Member.COOKIE_USERNAME_NAME, member.getUsername());
//		WebUtils.addCookie(request, response, Member.COOKIE_PASS_NAME, cookiePass);
		return Message.success("注册成功,请登录...");
	}


	/**
	 * 注销
	 */
	@ResponseBody
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public Message logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		session.removeAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
		WebUtils.removeCookie(request, response, Member.COOKIE_USERNAME_NAME);
		WebUtils.removeCookie(request, response, Member.COOKIE_PASS_NAME);
		return Message.success("成功退出登录");
	}




}